﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BCMS.Business.Implementation;
using BCMS.Business.DataContract;
using BCMS.Settings;
using BCMS.FrontEnd.DataContract;

namespace BCMS.Forms
{
    public partial class frmCoupon : Form
    {
        //public string Serial { set; get; }
        frmMain _parentForm;
        DateTime ClaimDate { set; get; }
        CouponUI cp = null;

        public frmCoupon()
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();
        }

        public frmCoupon(frmMain main, DateTime claimDate)
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();
            _parentForm = main;
            this.ClaimDate = claimDate;
        }

        public frmCoupon(CouponUI item, frmMain main)
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();
            _parentForm = main;
            cp = item;

            txtAlphaCode.Text = item.Serial.Split('-')[0];
            txtNumCode.Text = item.Serial.Split('-')[1];
            txtParValue.Value = Convert.ToInt64(item.ParValue);
            txtStartDate.Text = item.StartDate.ToString("yyyy/MM/dd");
            txtExpireDate.Text = item.ExpireDate.ToString("yyyy/MM/dd");
            txtRName.Text = item.ReleaseName.ToString();
            txtStatus.Text = item.Status;
            txtRTarget.Text = item.ReleaseTarget;
            txtRKind.Text = item.ReleaseKind;
            txtRDetail.Text = item.ReleaseDetail;
            txtRNote.Text = item.ReleaseNote;
            txtNote.Text = item.Note;
            btnClaim.Enabled = false;
            btnUndo.Enabled = false;

            if (item.Status.Equals(Params.NORMAL))
            {
                btnClaim.Enabled = true;
                btnClaim.Focus();
            }
            else if (item.Status.Equals(Params.CLAIMED))
            {
                btnUndo.Enabled = true;
                btnUndo.Focus();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtNumCode_Leave(object sender, EventArgs e)
        {
            try
            {
                string[] series = txtNumCode.Text.Split('-');

                if (series.Length.Equals(1))
                {
                    getCouponInfo(txtAlphaCode.Text + "-" + txtNumCode.Text);
                }
                else
                {
                    txtStartDate.Text = string.Empty;
                    txtExpireDate.Text = string.Empty;
                    txtParValue.Text = string.Empty;
                    txtRName.Text = string.Empty;
                    txtNote.Text = "Thu theo lô: " + dtClaim.Value.ToString("dd/MM/yyyy");

                    txtRName.Text = string.Empty;
                    txtRTarget.Text = string.Empty;
                    txtRKind.Text = string.Empty;
                    txtRDetail.Text = string.Empty;
                    txtStatus.Text = string.Empty;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error getting coupon. Error: " + ex.Message);
            }
        }

        private void frmCoupon_Load(object sender, EventArgs e)
        {
            txtAlphaCode.Focus();
            dtClaim.Value = ClaimDate;
        }

        private void btnClaim_Click(object sender, EventArgs e)
        {
            try
            {
                DALclient client = new DALclient();
                string[] series = txtNumCode.Text.Split('-');

                if (series.Length > 1)
                {
                    client.batchClaim(getSerialsFromUI(), GlobalVars.activeUser, txtNote.Text, dtClaim.Value.Date);
                    GlobalVars.ShowInfo("Thu hồi [THÀNH CÔNG] " + getSerialsFromUI().Count + " phiếu.");
                }
                else
                {

                    if (cp != null)
                    {
                        if (cp.Status.Equals(Params.CLAIMED))
                        {
                            GlobalVars.ShowWarning("Coupon: [" + cp.Serial +
                                            "] [ĐÃ ĐƯỢC THU HỒI] bởi [" + cp.ClaimBy + "]");
                            ResetUI();
                            return;
                        }

                        if (cp.Status.Equals(Params.DISPOSED))
                        {
                            GlobalVars.ShowWarning("Coupon: [" + cp.Serial +
                                            "] không hợp lệ vì [ĐÃ HỦY].");
                            ResetUI();
                            return;
                        }

                        if (cp.ExpireDate < dtClaim.Value.Date)
                        {
                            GlobalVars.ShowError("Coupon: [" + cp.Serial +
                                            "] cần phải gia hạn vì [ĐÃ HẾT HẠN].");
                            ResetUI();
                            return;
                        }

                        btnClaim.Enabled = false;

                        client.claimCouponBySerial(getSerialFromUI(), GlobalVars.activeUser, dtClaim.Value.ToString(), dtClaim.Value.Date);
                        cp.Status = Params.CLAIMED;
                        cp.ClaimBy = GlobalVars.activeUser;
                        cp.Note = txtNote.Text;
                        cp.ClaimDate = dtClaim.Value;

                        GlobalVars.ShowInfo("Thu hồi [THÀNH CÔNG] coupon: [" + getSerialFromUI() + "]");
                        SortableBindingList<CouponUI> couponList = _parentForm.grvCoupons.DataSource as SortableBindingList<CouponUI>;
                        if (couponList != null)
                        {
                            couponList.Insert(0, cp);
                            updateSummary();
                        }
                        else
                            _parentForm.updateCouponsList();


                        ResetUI();
                        txtAlphaCode.Focus();
                    }

                }
            }
            catch (Exception ex)
            {
                GlobalVars.ShowError("Không thu hồi được coupon\n\nError: " + ex.Message);
                return;
            }
        }

        private void updateSummary()
        {
            SortableBindingList<CouponUI> couponList = _parentForm.grvCoupons.DataSource as SortableBindingList<CouponUI>;
            if (couponList != null)
            {

                long totalQtty = Convert.ToInt64(_parentForm.txtTotalQtty.Value);
                long totalValue = Convert.ToInt64(_parentForm.txtTotalValue.Value);

                totalQtty++;
                totalValue += Convert.ToInt64(cp.ParValue);

                _parentForm.txtTotalQtty.Value = totalQtty;
                _parentForm.txtTotalValue.Value = totalValue;
            }
            else
            {
                DALclient client = new DALclient();
                List<CouponUI> list = client.getCouponsByClaim(GlobalVars.activeUser, "-", DateTime.Today, DateTime.Today.AddDays(1));

                if (list != null)
                {
                    _parentForm.grvCoupons.DataSource = new SortableBindingList<CouponUI>(list);
                    _parentForm.formatCouponGrid(_parentForm.grvCoupons);
                    _parentForm.updateCouponsSummary(_parentForm.grvCoupons);
                }
            }
        }

        private string getSerialFromUI()
        {
            return txtAlphaCode.Text + "-" + txtNumCode.Text;
        }

        private void getCouponInfo(string serial)
        {
            try
            {
                DALclient client = new DALclient();
                cp = client.getCouponBySerial(serial);

                if (cp != null)
                {
                    txtParValue.Value = Convert.ToInt64(cp.ParValue);
                    txtStartDate.Text = cp.StartDate.ToString("yyyy/MM/dd");
                    txtExpireDate.Text = cp.ExpireDate.ToString("yyyy/MM/dd");
                    txtRName.Text = cp.ReleaseName.ToString();
                    txtStatus.Text = cp.Status;
                    txtRTarget.Text = cp.ReleaseTarget;
                    txtRKind.Text = cp.ReleaseKind;
                    txtRDetail.Text = cp.ReleaseDetail;
                    txtNote.Text = cp.Note;
                    txtRNote.Text = cp.ReleaseNote;
                    if (cp.Status.Equals(Params.NORMAL))
                    {
                        btnClaim.Enabled = true;
                        btnUndo.Enabled = false;
                        btnClaim.Focus();
                    }
                    else if (cp.Status.Equals(Params.CLAIMED))
                    {
                        btnUndo.Enabled = true;
                        btnClaim.Enabled = false;
                        btnUndo.Focus();
                    }
                }
                else
                {
                    GlobalVars.ShowWarning("Không tìm thấy coupon: [" +
                                    txtAlphaCode.Text + "-" + txtNumCode.Text + "]");
                    ResetUI();
                    txtAlphaCode.SelectAll();
                }
            }
            catch (Exception ex)
            {
                GlobalVars.ShowError("Lỗi thu hồi coupons: " + txtAlphaCode.Text + "-" + txtNumCode.Text +
                                "\nError: " + ex.Message);
            }

        }

        private List<string> getSerialsFromUI()
        {
            string[] series = txtNumCode.Text.Split('-');
            int clow = Convert.ToInt32(series[0]);
            int chigh = Convert.ToInt32(series[1]);
            List<string> list = new List<string>();
            for (int i = clow; i <= chigh; i++)
                list.Add(txtAlphaCode.Text + "-" + i.ToString());

            return list;
        }

        private void ResetUI()
        {
            cp = null;
            btnClaim.Enabled = false;
            btnUndo.Enabled = false;
            txtNumCode.Text = string.Empty;
            txtStartDate.Text = string.Empty;
            txtExpireDate.Text = string.Empty;
            txtParValue.Text = string.Empty;
            txtRName.Text = string.Empty;
            txtNote.Text = string.Empty;
            txtRName.Text = string.Empty;
            txtRTarget.Text = string.Empty;
            txtRKind.Text = string.Empty;
            txtRDetail.Text = string.Empty;
            txtStatus.Text = string.Empty;
        }

        private void btnUndo_Click(object sender, EventArgs e)
        {
            try
            {
                if (cp != null)
                {
                    btnClaim.Enabled = false;
                    DALclient client = new DALclient();

                    if (GlobalVars.activeUser.Equals(cp.ClaimBy) || GlobalVars.activeRoles.Equals("1111"))
                        client.undoClaimCouponBySerial(getSerialFromUI(), GlobalVars.activeUser);

                    GlobalVars.ShowInfo("[HỦY] Thu hồi [THÀNH CÔNG] coupon: [" + getSerialFromUI() + "]");
                    _parentForm.updateCouponsList();

                    updateSummary();
                    ResetUI();
                    txtAlphaCode.Focus();
                }
            }
            catch (Exception ex)
            {
                GlobalVars.ShowError("Không thu hồi được coupon:[" + cp.Serial
                                    + "]\nError: " + ex.Message);
                return;
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            const int WM_KEYDOWN = 0x100;
            if (msg.Msg == WM_KEYDOWN)
            {
                if (keyData == Keys.Escape)
                {
                    this.Close();
                    return true;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void dtClaim_ValueChanged(object sender, EventArgs e)
        {
            Params.CDate = dtClaim.Value.Date;
        }
    }
}
